﻿using AutoMapper;
using BaseAPI;
using MemorySiteServer.AuthManage;
using MemorySiteServer.Models;
using MemorySiteServer.ViewModels.RoleViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Snowflake.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MemorySiteServer.Controllers
{
    /// <summary>
    /// 角色
    /// </summary>
    [ApiController]
    public class RoleController : BaseController<Role>
    {
        public RoleController(DataContext context, IMapper mapper, IdWorker idWorker) : base(context, mapper, idWorker) { }

        /// <summary>
        /// 获取授权接口列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/[controller]/[action]")]
        [Authorize(Policy = "site")]
        public async Task<ResponseModel<List<AllPermissionResponse>>> GetPermissionList()
        {
            return ResponseModel<List<AllPermissionResponse>>.Success(await AllPermissionResponse.GetAllPermissionsAsync());
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="roleCreateRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/[controller]/[action]")]
        [Authorize(Policy = "site")]
        public async Task<ResponseModel<string>> Create(RoleCreateRequest roleCreateRequest)
        {
            var user = JwtServer.GetUser(GetUserID());
            if (roleCreateRequest.Level <= user.Role.Level)
                return ResponseModel<string>.Failed("新添加的角色权限等级错误");
            else
                return await Z_Create(roleCreateRequest);
        }

        /// <summary>
        /// 获取角色列表（不含权限）
        /// </summary>
        /// <param name="roleGetListRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/[controller]/[action]")]
        [Authorize(Policy = "site")]
        public async Task<ResponseModel<List<Role>>> GetList(RoleGetListRequest roleGetListRequest)
        {
            return await Z_GetList(roleGetListRequest);
        }

        /// <summary>
        /// 获取某一角色权限列表
        /// </summary>
        /// <param name="roleGetOneRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/[controller]/[action]")]
        [Authorize(Policy = "site")]
        public async Task<ResponseModel<Role>> GetOne(RoleGetOneRequest roleGetOneRequest)
        {
            return await Z_GetOne(roleGetOneRequest);
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="rolePatchRequest"></param>
        /// <returns></returns>
        [HttpPatch]
        [Route("api/[controller]/[action]")]
        [Authorize(Policy = "site")]
        public async Task<ResponseModel<string>> Modify(RolePatchRequest rolePatchRequest)
        {
            var user = JwtServer.GetUser(GetUserID());
            //验证是否越权
            var rolePatchUser = await controllerServer.GetOne(rolePatchRequest.ID, queryable => queryable.Select(x => new Role() { Level = x.Level }));
            if (rolePatchUser.Code == 0)
                return ResponseModel<string>.Failed(rolePatchUser.Message);
            var level = rolePatchUser.Data.Level;
            if (level <= user.Role.Level)
                return ResponseModel<string>.Failed("角色权限等级错误");
            //验证是否虚加权限
            foreach (var x in rolePatchRequest.RolePermissions)
            {
                if (!user.Role.RolePermissions.Exists(y => y.Action == x.Action))
                    return ResponseModel<string>.Failed($"{x.Action}越权");
            };
            var roleResponse = await GetOne(new RoleGetOneRequest() { ID = rolePatchRequest.ID });
            if (roleResponse.Code == 0)
                return ResponseModel<string>.Failed(roleResponse.Message);
            rolePatchRequest.SetOriginalRolePermissions(roleResponse.Data.RolePermissions);
            var result = await Z_Modify(rolePatchRequest);
            if (result.Code == 1)
            {
                //刷新JwtServer中的角色权限
                JwtServer.UpdateRole((await controllerServer.GetOne(rolePatchRequest.ID)).Data);
            }
            return result;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("api/[controller]/[action]")]
        [Authorize(Policy = "site")]
        public async Task<ResponseModel<string>> Delete(long id)
        {
            var user = JwtServer.GetUser(GetUserID());
            var roleResponse = await controllerServer.GetOne(id);
            if (roleResponse.Code == 0)
                return ResponseModel<string>.Failed(roleResponse.Message);
            var role = roleResponse.Data;
            //这里小于等于就不用验证自我删除
            if (role.Level <= user.Role.Level)
                return ResponseModel<string>.Failed("权限不足");
            var result = await Z_Delete(id);
            if (result.Code == 1)
            {
                JwtServer.ReplaceRole(id, (await controllerServer.GetOne(2)).Data);
            }
            return result;
        }
    }
}
